1 /****************************** Module Header ******************************\
2 Module Name: NativeMethods.cpp
3 Project: CppCLINativeDllWrapper
4 Copyright (c) Microsoft Corporation.
6 The code in this file implements the C++/CLI wrapper classes that allow you
7 to call from any .NET code to the functions exported by a native C++ DLL
10 CSCallNativeDllWrapper/VBCallNativeDllWrapper (any .NET clients)
12 CppCLINativeDllWrapper (this C++/CLI wrapper)
14 CppDynamicLinkLibrary (a native C++ DLL module)
16 The NativeMethods class wraps the global functions exported by
17 CppDynamicLinkLibrary.dll.
19 The interoperability features supported by Visual C++/CLI offer a
20 particular advantage over other .NET languages when it comes to
21 interoperating with native modules. Apart from the traditional explicit
22 P/Invoke, C++/CLI allows implicit P/Invoke, also known as C++ Interop, or
23 It Just Work (IJW), which mixes managed code and native code almost
24 invisibly. The feature provides better type safety, easier coding, greater
25 performance, and is more forgiving if the native API is modified. You can
26 use the technology to build .NET wrappers for native C++ classes and
27 functions if their source code is available, and allow any .NET clients to
28 access the native C++ classes and functions through the wrappers.
30 This source is subject to the Microsoft Public License.
31 See http://www.microsoft.com/opensource/licenses.mspx#Ms-PL.
32 All other rights reserved.
34 THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND,
35 EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
36 WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE.
37 \***************************************************************************/
39 #pragma region Includes
40 #include "NativeMethods.h"
41 using namespace CppCLINativeDllWrapper
;
43 #include <msclr/marshal.h>
44 using namespace msclr::interop
;
48 int NativeMethods::GetStringLength1(String
^ str
)
50 // Marshal System::String to PCWSTR, and call the C++ function.
51 marshal_context
^ context
= gcnew
marshal_context();
52 PCWSTR pszString
= context
->marshal_as
<const wchar_t*>(str
);
53 int length
= ::GetStringLength1(pszString
);
58 int NativeMethods::GetStringLength2(String
^ str
)
60 // Marshal System::String to PCWSTR, and call the C++ function.
61 marshal_context
^ context
= gcnew
marshal_context();
62 PCWSTR pszString
= context
->marshal_as
<const wchar_t*>(str
);
63 int length
= ::GetStringLength2(pszString
);
68 int NativeMethods::Max(int a
, int b
, CompareCallback
^ cmpFunc
)
70 // Convert the delegate to a function pointer.
71 IntPtr pCmpFunc
= Marshal::GetFunctionPointerForDelegate(cmpFunc
);
72 return ::Max(a
, b
, static_cast<::PFN_COMPARE
>(pCmpFunc
.ToPointer()));